package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Optional;

/**
 * 入住Service业务层处理
 * 
 * @author tfx
 * @date 2025-05-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper  bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper  contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已经入住
        //通过身份证号查询老人信息
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.in(Elder::getStatus,1,2,4);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)){
            throw new RuntimeException("该老人已经入住");
        }

        //更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或更新老人数据
        elder = insertOrUpdate(bed,dto.getCheckInElderDto());

        //生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();

        //新增签约办理
        inserContract(contractNo,elder,dto);

        //新增入住记录
        CheckIn checkIn = insertCheckIn(elder,dto);

        //新增入住配置信息
        insertCheckInConfig(checkIn.getId(),dto);
    }
    /**
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getDetail(Integer id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = getById(id);
        //老人信息
        Optional.ofNullable(elderMapper.selectById(checkIn.getElderId()))
                .ifPresent(e -> {
                    CheckInElderVo elderVo = BeanUtil.toBean(e, CheckInElderVo.class);
                    //  设置年龄
                    int age = IdcardUtil.getAgeByIdCard(e.getIdCardNo());
                    elderVo.setAge(age);
                    vo.setCheckInElderVo(elderVo);
                });
        //家属信息
        String jsonString = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(jsonString, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVoList);
        //入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        // 开始日期与结束日期
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfigVo);
        //合同信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));
        vo.setContract(contract);
        return vo;
    }

    /**
     * 新增入住配置信息
     * @param id
     * @param dto
     */
    private void insertCheckInConfig(Long id, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住记录
     * @param elder
     * @param dto
     * @return
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param contractNo
     * @param elder
     * @param dto
     */
    private void inserContract(String contractNo, Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setContractName(elder.getName() + "入住合同");
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        Integer status = startDate.isBefore(LocalDateTime.now())?0 : 1;
        contract.setStatus(status);
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contractMapper.insert(contract);

    }

    /**
     * 新增或更新老人数据
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //准备老人数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        //查新老人信息
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(elderDb)){
            //新增
            elderMapper.insert(elder);
        }else {
            //更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }


}
